package level4.helpers
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLRequest;
	import flash.utils.clearTimeout;
	import flash.utils.setTimeout;
	
	import level4.assets.AssetsManager;
	import level4.project.Project;
	
	/**
	 * 反射工具
	 * */
	public class ReflectHelper
	{
		/**
		 * 加载一个swf,并在callback中放入此swf的程序域,以后可以通过此域来反射其中的类.
		 * 卸载通过AssetsManager来进行
		 * 
		 * @param url,swf的url
		 * @param callback,载入完毕后调用,方法签名: function(domain:ApplicationDomain,...args):void
		 * @param progressCallBack,加载过程中调用,方法签名:progressCallBack(curBytes,totalBytes):void
		 * @param ...args,传递进callback的参数列表
		 * */
		public static function loadExportedThatApplicationDomain(url:String,callback:Function, progressCallBack:Function = null,...args):void{
//			url = url + "?version=" + Project.VERSION;
			var isLoaded:Boolean = false;
			
			var l:Loader = new Loader();
			addListeners();
			l.load(new URLRequest(url));
			
			////////////
			//闭包
			////////////
			function addListeners():void{
				l.contentLoaderInfo.addEventListener(Event.COMPLETE,onComplete);
				l.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,onIoError);
				l.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,onProgress);
			}
			function removeListeners():void{
				l.contentLoaderInfo.removeEventListener(Event.COMPLETE,onComplete);
				l.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR,onIoError);
				l.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,onProgress);
			}
			function onComplete(e:Event):void{
				isLoaded = true;
				removeListeners();
				//表明加载已经完成了
				if(progressCallBack != null)
					progressCallBack(100, 100);
				
				if(callback != null){
					callback(l.contentLoaderInfo.applicationDomain,args);
				}
				//保持好 这个Loader,
				AssetsManager.addOneLoader(url,l);
			}
			function onIoError(e:Event):void{
				removeListeners();
				l.unload();
				if(callback != null)
					callback(null);
				throw("ReflectHelper的ioError,url:"+url);
			}
			function onProgress(e:ProgressEvent):void{
				//此处解决,载入完毕,flash player不发出COMPLETE事件的bug
				if(e.bytesLoaded == e.bytesTotal){
					var timerId:int = setTimeout(function():void{
						clearTimeout(timerId);
						if(!isLoaded){
							onComplete(null);				
						}
					},200);
				}
				if(progressCallBack != null)
					progressCallBack(e.bytesLoaded, e.bytesTotal);
			}
		}
	}
}